package br.com.cadastro.desktop;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jdesktop.application.Action;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.TaskMonitor;

import br.com.cadastro.hibernate.util.HibernateUtil;

/**
 * The application's main frame.
 */
public class SGERunView extends FrameView {

	private Server server;
	
    public SGERunView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }
    
    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = SGERunApp.getApplication().getMainFrame();
            aboutBox = new SGERunAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        SGERunApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jettyPainel = new javax.swing.JPanel();
        botaoJettyIniciar = new javax.swing.JButton();
        botaoJettyParar = new javax.swing.JButton();
        labelJetty = new javax.swing.JLabel();
        hiberantePainel = new javax.swing.JPanel();
        botaoHibernateParar = new javax.swing.JButton();
        botaoHibernateIniciar = new javax.swing.JButton();
        labelHibernate = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setLayout(new java.awt.GridLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(SGERunApp.class).getContext().getResourceMap(SGERunView.class);
        jettyPainel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("JettyPainel.border.title"))); // NOI18N
        jettyPainel.setName("JettyPainel"); // NOI18N

        botaoJettyIniciar.setText(resourceMap.getString("botaoJettyIniciar.text")); // NOI18N
        botaoJettyIniciar.setName("botaoJettyIniciar"); // NOI18N
        botaoJettyIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoJettyIniciarActionPerformed(evt);
            }
        });

        botaoJettyParar.setText(resourceMap.getString("botaoJettyParar.text")); // NOI18N
        botaoJettyParar.setEnabled(false);
        botaoJettyParar.setName("botaoJettyParar"); // NOI18N
        botaoJettyParar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoJettyPararActionPerformed(evt);
            }
        });

        labelJetty.setBackground(resourceMap.getColor("labelJetty.background")); // NOI18N
        labelJetty.setText(resourceMap.getString("labelJetty.text")); // NOI18N
        labelJetty.setName("labelJetty"); // NOI18N

        javax.swing.GroupLayout jettyPainelLayout = new javax.swing.GroupLayout(jettyPainel);
        jettyPainel.setLayout(jettyPainelLayout);
        jettyPainelLayout.setHorizontalGroup(
            jettyPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jettyPainelLayout.createSequentialGroup()
                .addGroup(jettyPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jettyPainelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(botaoJettyIniciar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoJettyParar))
                    .addGroup(jettyPainelLayout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(labelJetty)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jettyPainelLayout.setVerticalGroup(
            jettyPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jettyPainelLayout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jettyPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoJettyIniciar)
                    .addComponent(botaoJettyParar))
                .addGap(45, 45, 45)
                .addComponent(labelJetty)
                .addContainerGap(61, Short.MAX_VALUE))
        );

        mainPanel.add(jettyPainel);

        hiberantePainel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("HibernatePainel.border.title"))); // NOI18N
        hiberantePainel.setName("HibernatePainel"); // NOI18N

        botaoHibernateParar.setText(resourceMap.getString("botaoHibernateIniciar.text")); // NOI18N
        botaoHibernateParar.setName("botaoHibernateIniciar"); // NOI18N
        botaoHibernateParar.setEnabled(false);
        botaoHibernateParar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoHibernatePararActionPerformed(evt);
            }
        });

        botaoHibernateIniciar.setText(resourceMap.getString("botaoHibernateParar.text")); // NOI18N
        botaoHibernateIniciar.setName("botaoHibernateParar"); // NOI18N
        
        botaoHibernateIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoHibernateIniciarActionPerformed(evt);
            }
        });

        labelHibernate.setBackground(resourceMap.getColor("labelHibernate.background")); // NOI18N
        labelHibernate.setText(resourceMap.getString("labelHibernate.text")); // NOI18N
        labelHibernate.setName("labelHibernate"); // NOI18N

        javax.swing.GroupLayout hiberantePainelLayout = new javax.swing.GroupLayout(hiberantePainel);
        hiberantePainel.setLayout(hiberantePainelLayout);
        hiberantePainelLayout.setHorizontalGroup(
            hiberantePainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(hiberantePainelLayout.createSequentialGroup()
                .addGroup(hiberantePainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(hiberantePainelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(botaoHibernateIniciar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoHibernateParar))
                    .addGroup(hiberantePainelLayout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(labelHibernate)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        hiberantePainelLayout.setVerticalGroup(
            hiberantePainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(hiberantePainelLayout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(hiberantePainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoHibernateIniciar)
                    .addComponent(botaoHibernateParar))
                .addGap(44, 44, 44)
                .addComponent(labelHibernate)
                .addContainerGap(62, Short.MAX_VALUE))
        );

        mainPanel.add(hiberantePainel);

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(SGERunApp.class).getContext().getActionMap(SGERunView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 146, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>

    private void botaoJettyIniciarActionPerformed(java.awt.event.ActionEvent evt) {
    	server = new Server();
        SocketConnector connector = new SocketConnector();

        // Set some timeout options to make debugging easier.
        connector.setMaxIdleTime(1000 * 60 * 60);
        connector.setSoLingerTime(-1);
        connector.setPort(8080);
        server.setConnectors(new Connector[] { connector });

        WebAppContext bb = new WebAppContext();
        bb.setServer(server);
        bb.setContextPath("/");
        bb.setWar("cadastro-1.0-SNAPSHOT");

        // START JMX SERVER
        // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
        // server.getContainer().addEventListener(mBeanContainer);
        // mBeanContainer.start();

        server.setHandler(bb);
        
        try {
            labelJetty.setText("Iniciando...");
            server.start();
            labelJetty.setText("Iniciado");
            botaoJettyParar.setEnabled(true);
            botaoJettyIniciar.setEnabled(false);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(100);
        }

       
    }

    private void botaoJettyPararActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		labelJetty.setText("Parando...");
			server.stop();
			server.join();
			labelJetty.setText("Parado");
			botaoJettyParar.setEnabled(false);
	        botaoJettyIniciar.setEnabled(true);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}
		System.out.println(">>>>PARANDO SERVIDOR JETTY<<<<<");
        
    }

    private void botaoHibernatePararActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void botaoHibernateIniciarActionPerformed(java.awt.event.ActionEvent evt) {
    	labelHibernate.setText("Iniciando");
    	HibernateUtil.getSessionFactory();
    	labelHibernate.setText("Iniciado");
    	botaoHibernateIniciar.setEnabled(false);
    }

    // Variables declaration - do not modify
    private javax.swing.JButton botaoHibernateParar;
    private javax.swing.JButton botaoHibernateIniciar;
    private javax.swing.JButton botaoJettyIniciar;
    private javax.swing.JButton botaoJettyParar;
    private javax.swing.JPanel hiberantePainel;
    private javax.swing.JPanel jettyPainel;
    private javax.swing.JLabel labelHibernate;
    private javax.swing.JLabel labelJetty;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
